<?php
	class AdsBanner extends LilAdsAppModel {
		var $name = 'AdsBanner';
		var $validate = array(
			'title' => array('rule'=>array('minLength', '1'), 'required'=>true),
			'link' => array('rule'=>'url', 'allowEmpty'=>true),
			'kind' => array('format' => array('rule' => array('custom', '/^(I|H|P|F)$/'))),
			'width' => array('rule'=>'numeric', 'allowEmpty'=>true),
			'height' => array('rule'=>'numeric', 'allowEmpty'=>true),
		);

		var $actsAs = array(
			'LilUpload.LilUpload'=>array(
				'fileField'         => 'filename',
				'allowedExt'        => array('gif', 'jpg', 'png', 'swf'),
				'overwriteExisting' => false,
				'baseDir'           => '{WWW_ROOT}img{DS}ads{DS}',
				'fileFormat'        => '{$full_name}',
				'dirFormat'         => ''
		));
		
		function __construct($id = false, $table = null, $ds = null) {		
			$this->actsAs['LilUpload.LilUpload']['baseDir'] = Configure::read('LilAds.uploadFolder');
			parent::__construct($id, $table, $ds);
		}

		function findForLocation($location_id=null) {
			$Location = ClassRegistry::init('LilAds.AdsLocation');
			if (is_numeric($location_id) && $location_data = $Location->read(null, $location_id)) {
				$conditions = array();
				$conditions['AdsCampaign.active'] = 1;
				
				$conditions['AdsBanner.kind'] = array();
				if (!empty($location_data['AdsLocation']['accept_image'])) $conditions['AdsBanner.kind'][] = 'I';
				if (!empty($location_data['AdsLocation']['accept_flash'])) $conditions['AdsBanner.kind'][] = 'F';
				if (!empty($location_data['AdsLocation']['accept_html']))  $conditions['AdsBanner.kind'][] = 'H';
				if (!empty($location_data['AdsLocation']['accept_plain'])) $conditions['AdsBanner.kind'][] = 'P';
				if (empty($conditions['AdsBanner.kind'])) unset($conditions['AdsBanner.kind']);
				
				if (!empty($location_data['AdsLocation']['width'])) $conditions['AdsBanner.width'] = $location_data['AdsLocation']['width'];
				if (!empty($location_data['AdsLocation']['height'])) $conditions['AdsBanner.height'] = $location_data['AdsLocation']['height'];
				
				$conditions[] = array('OR'=>array(0=>array('AdsCampaign.limit_start'=>null), 1=>array('AdsCampaign.limit_start <='=>strftime('%Y-%m-%d'))));
				$conditions[] = array('OR'=>array(0=>array('AdsCampaign.limit_end'=>null), 1=>array('AdsCampaign.limit_end >='=>strftime('%Y-%m-%d'))));
				$conditions[] = array('OR'=>array(0=>array('AdsCampaign.limit_views'=>null), 1=>array('AdsCampaign.views >='=>'AdsCampaign.limit_views')));
				$conditions[] = array('OR'=>array(0=>array('AdsCampaign.limit_clicks'=>null), 1=>array('AdsCampaign.clicks >='=>'AdsCampaign.limit_clicks')));
				
				App::import('Model', array('LilAds.AdsCampaign', 'LilAds.AdsAction'));
				$action = ClassRegistry::init('LilAds.AdsAction');
				$this->bindModel(array('belongsTo' => array('AdsCampaign' => array('type' => 'INNER'))));
				
				if ($banner = $this->find('first', array('conditions' => $conditions, 'order'=>'(4 - AdsCampaign.priority) * RAND() DESC'))) {
					$banner['AdsLocation'] = $location_data['AdsLocation'];
					$db =& ConnectionManager::getDataSource($this->useDbConfig);
					$db->execute("UPDATE ".$this->AdsCampaign->table." SET views=views+1 WHERE id=".$banner['AdsCampaign']['id']);
					$db->execute("UPDATE ".$action->table." SET views=views+1 WHERE ads_campaign_id=".$banner['AdsCampaign']['id']." AND ads_banner_id=".$banner['AdsBanner']['id']." AND date_hour='".strftime('%Y-%m-%d %H:00:00')."'");
					if (!$db->affected) {
						$db->execute("INSERT INTO ".$action->table." (ads_campaign_id, ads_banner_id, date_hour, views) VALUES (".$banner['AdsCampaign']['id'].",".$banner['AdsBanner']['id'].",'".strftime('%Y-%m-%d %H:00:00')."',1)");
					}
					return $banner;
				}
			}
			return false;
		}

		function click($id=null) {
			if (is_numeric($id) && $banner = $this->find('first', array('conditions' => array('AdsBanner.id' => $id), 'recursive' => -1))) {
				$Action = ClassRegistry::init('LilAds.AdsAction');
				$Campaign = ClassRegistry::init('LilAds.AdsCampaign');
				
				$Campaign->updateAll(
					array('clicks' => 'clicks + 1'),
					array('id'     => $banner['AdsBanner']['ads_campaign_id'])
				);
				
				$db =& ConnectionManager::getDataSource($this->useDbConfig);
				$db->execute(sprintf(
					'UPDATE %1$s SET clicks=clicks+1 WHERE ads_campaign_id=%2$d AND ads_banner_id=%3$d AND date_hour=\'%4$s\'',
					$Action->table,
					$banner['AdsBanner']['ads_campaign_id'],
					$banner['AdsBanner']['id'],
					strftime('%Y-%m-%d %H:00:00')
				));
				
				if (!$db->affected) {
					$db->execute(sprintf(
						'INSERT INTO %1$s (ads_campaign_id, ads_banner_id, date_hour, clicks) VALUES (%2$d, %3$d, %4$s, 1)',
						$Action->table,
						$banner['AdsBanner']['ads_campaign_id'],
						$banner['AdsBanner']['id'],
						strftime('%Y-%m-%d %H:00:00')
					));
				}
				return $banner['AdsBanner']['link'];
			}
			return false;
		}
	}
?>